<?php
class Grading extends CI_Controller {

	function __construct()
	{
		parent::__construct();	
		$this->load->helper('flexigrid');
		$this->load->library('flexigrid');
		$this->load->library('form_validation');
		$this->load->model('master_model');
		$this->load->model('pelajaran_model');
	}
	
	function index($kode_mp,$id_sekolah,$id_ta,$act='')
	{
		/*
		 * 0 - display name
		 * 1 - width
		 * 2 - sortable
		 * 3 - align
		 * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
		 */
		// $colModel['no'] = array('No',40,TRUE,'center',0);
		if($this->session->userdata('roleid')=='0') //diknas
			$colModel['NAMA_SEKOLAH'] = array('Nama Sekolah',100,TRUE,'center',1);
		$colModel['NAMA_TA'] = array('Tahun Ajaran',100,TRUE,'center',1);
		$colModel['KODE_MATA_PELAJARAN'] = array('Mata Pelajaran',100,TRUE,'center',1);
		// $colModel['KODE_PENILAIAN'] = array('Aspek Penilaian',300,TRUE,'center',1);
		$colModel['GRADE'] = array('Nilai',300,TRUE,'center',0);
		$colModel['ubah'] = array('Edit',50,FALSE,'center',0);
		
		/*
		 * Aditional Parameters
		 */
		$gridParams = array(
		'width' => 'auto',
		'height' => '345',
		'rp' => 10,
		'rpOptions' => '[10,15,20,25,40]',
		'pagestat' => 'Displaying: {from} to {to} of {total} items.',
		'blockOpacity' => 0.5,
		'title' => 'Daftar Grading Per Mata Pelajaran'
		);
		
		/*
		 * 0 - display name
		 * 1 - bclass
		 * 2 - onpress
		 */
		$enable_add = $this->pelajaran_model->enableAddGrading($kode_mp)->num_rows();
		// var_dump($enable_add);
		if($enable_add == 0)
		$buttons[] = array('Add','add','org_js');
		// $buttons[] = array('separator');
		// $buttons[] = array('Select All','add','org_js');
		// $buttons[] = array('Deselect All','delete','org_js');
		// $buttons[] = array('separator');
		$buttons[] = array('Back to Pelajaran','back','org_js');
		
		//Build js
		$grid_js = build_grid_js('flex1',site_url("/grading/listgrading_grid/".$kode_mp."/".$id_sekolah."/".$id_ta),$colModel,'no','asc',$gridParams,$buttons);
		
		if($this->session->flashdata('suc_msg'))
			$data['header_info'] = '<div class="ret_success">'.$this->session->flashdata('suc_msg').'</div>';
		
		$data['title'] = "Contoh Flexigrid";
		$data['info'] = "Flexigrid";
		$data['js_grid'] = $grid_js;
		$data['version'] = "0.36";
		$data['download_file'] = "Flexigrid_CI_v0.36.rar";
		
		$data['added_js'] = 
			"<script type='text/javascript'>
			function org_js(com,grid)
			{
				if (com=='Select All')
				{
					$('.bDiv tbody tr',grid).addClass('trSelected');
				}
				
				if (com=='Deselect All')
				{
					$('.bDiv tbody tr',grid).removeClass('trSelected');
				}
				
				if (com=='Add')
				{
					 location.href='".base_url()."index.php/grading/input_grading/".$kode_mp."'; 
				}
				
				if (com=='Back to Pelajaran')
				{
					location.href='".base_url()."index.php/ms_pelajaran/'; 
				}
				
				if (com=='Delete')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin ingin menghapus ' + $('.trSelected',grid).length + ' buah data?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '".site_url('/grading/delete_grading')."',
							   data: 'items='+itemlist,
							   success: function(data){
								$('#flex1').flexReload();
								alert(data);
							   }
							});
						}
					} else {
						return false;
					} 
				}          
			} 
			</script>
			";
			
		$data['content'] = $this->load->view('grid',$data,true);
		$this->load->view('main',$data);
	}
	
	function listgrading_grid($kode_mp,$id_sekolah,$id_ta)
	{	
	
		//List of all fields that can be sortable. This is Optional.
		//This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
		// if($this->session->userdata('roleid')=='0') //diknas
			// $valid_fields = array('NAMA_SEKOLAH','NAMA_TA','KODE_MATA_PELAJARAN','NAMA_MATA_PELAJARAN','KET');
		// else	
			$valid_fields = array('NAMA_TA','pel.NAMA_MATA_PELAJARAN','an.ASPEK_PENILAIAN','p.GRADE');
		
		$this->flexigrid->validate_post('p.NILAI_MIN','asc',$valid_fields);
		// $this->flexigrid->validate_post('p.NILAI_MIN','desc',$valid_fields);

		$records = $this->pelajaran_model->get_grading($kode_mp,$id_sekolah,$id_ta);
		
		// var_dump($records);
		$this->output->set_header($this->config->item('json_header'));
		$no = 0;
		/*
		 * Json build WITH json_encode. If you do not have this function please read
		 * http://flexigrid.eyeviewdesign.com/index.php/flexigrid/example#s3 to know how to use the alternative
		 */
		$pembanding = array();$pembanding[0]='';$i=1;
		foreach ($records['records']->result() as $row)
		{
			$pembanding[$i] = $row->KODE_MATA_PELAJARAN;
			if($this->session->userdata('roleid')=='0'){ //diknas
				$record_items[] = array($kode_mp.'#'.$id_sekolah.'#'.$id_ta.'#'.$row->KODE_PENILAIAN,
				$no+1,
				'<div align="left">'.$row->NAMA_SEKOLAH.'</div>',
				'<div align="left">'.$row->NAMA_TA .'</div>',
				'<div align="left">'.$row->NAMA_MATA_PELAJARAN .'</div>',
				// '<div align="left">'.$row->ASPEK_PENILAIAN .'</div>',
				'<div align="left">'.$row->NILAI_MIN .' - '.$row->NILAI_MAX .' : '.$row->GRADE .'<br>'.$row->NILAI_MIN .' - '.$row->NILAI_MAX .' : '.$row->GRADE.'</div>',
				'<a href=\''.site_url().'/grading/edit_grading/'.$kode_mp.'/'.$id_sekolah.'/'.$id_ta.'/'.$row->KODE_PENILAIAN.'/\'><img border=\'0\' src=\''.base_url().'images/main/28.png\'></a> 
				<a href=\''.site_url().'/grading/delete_grading/'.$kode_mp.'/'.$id_sekolah.'/'.$id_ta.'/'.$row->KODE_PENILAIAN.'/\'><img border=\'0\' src=\''.base_url().'images/delete.png\'></a>
				'
				);
				$no++;
			}else{
				if($pembanding[$i-1]!=$pembanding[$i]){
					$record_items[] = array($kode_mp.'#'.$id_sekolah.'#'.$id_ta,
					// $no+1,
					'<div align="left">'.$row->NAMA_TA .'</div>',
					'<div align="left">'.$row->NAMA_MATA_PELAJARAN .'</div>',
					// '<div align="left">'.$row->ASPEK_PENILAIAN .'</div>',
					'<div align="left">'.$row->NILAI_MIN .' - '.$row->NILAI_MAX .' : '.$row->GRADE .'</div>',
					'<a title="Edit Grading" href=\''.site_url().'/grading/edit_grading/'.$kode_mp.'/\'><img border=\'0\' src=\''.base_url().'images/main/28.png\'></a> &nbsp;
					<a title="Hapus Grading" href=\''.site_url().'/grading/delete_grading/'.$kode_mp.'/\'><img border=\'0\' src=\''.base_url().'images/delete.png\'></a>
					'
					);
					
				}else{
					$record_items[] = array($kode_mp.'#'.$id_sekolah.'#'.$id_ta,
					// '',
					'<div align="left"></div>',
					'<div align="left"></div>',
					// '<div align="left"></div>',
					'<div align="left">'.$row->NILAI_MIN .' - '.$row->NILAI_MAX .' : '.$row->GRADE .'</div>',
					''
					);
					
				}$no++;
			}
		$i++;}
		//Print please
		if(isset($record_items))
				$this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items));
			else
				$this->output->set_output('{"page":"1","total":"0","rows":[]}');
	}
	
	function cek_validasi() {	
			// Setting Rules
			$this->form_validation->set_rules('nilai_min1', 'Nilai Min', 'required|numeric');
			$this->form_validation->set_rules('nilai_max1', 'Nilai Max', 'required|numeric');
			$this->form_validation->set_rules('grade1', 'Grade', 'required');
			// $this->form_validation->set_rules('grade', 'NIP', 'required');
			if($this->session->userdata('roleid')=='0') //diknas
				$this->form_validation->set_rules('nama_sekolah', 'Nama Sekolah', 'required');
			
			// Setting Error Message
			$this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
			
			// Setting Delimiter
			$this->form_validation->set_error_delimiters('<li class="error">', '</li>');
			return $this->form_validation->run();
	}
	
	function cek_grading($kode_mp,$id_sekolah,$thn_ajaran,$id_aspek){
		$rs_cek = $this->pelajaran_model->validasi_grading($kode_mp,$id_sekolah,$thn_ajaran, $id_aspek)->row();
		return $rs_cek;
	}
	
	function input_grading($kode_mp)
    {
		if ($this->cek_validasi() == FALSE){
			$data['status'] = 'new';
			$data['param_id'] = $kode_mp."#".$this->session->userdata('unitid')."#".$this->session->userdata('tahunajaran');
			$data['tahunajaran'] = $this->pelajaran_model->getTa($this->session->userdata('unitid'));
			$data['pelajaran'] = $this->pelajaran_model->getMp($this->session->userdata('unitid'),$kode_mp);
			// $data['aspek_nilai'] = $this->pelajaran_model->getAspek($id_sekolah,$kode_mp);
			
			$data['content'] = $this->load->view('form_grading',$data,true);
			$this->load->view('main',$data);
		}
		else{
			$this->insert_grading($kode_mp);
		}            
    }
	
	function insert_grading($kode_mp){
		for($i=1; $i<=10; $i++){
			if($this->input->post('nilai_min'.$i)!='' and $this->input->post('nilai_max'.$i)!='' and $this->input->post('grade'.$i)!=''){
				$data = array(
					'TAHUN_AJARAN'			=> $this->session->userdata('tahunajaran'),
					'ID_SEKOLAH'			=> $this->session->userdata('unitid'),
					'KODE_MATA_PELAJARAN'	=> $kode_mp,	
					// 'KODE_PENILAIAN'		=> $this->input->post('kode_penilaian'),	
					'NILAI_MIN'				=> $this->input->post('nilai_min'.$i),	
					'NILAI_MAX'				=> $this->input->post('nilai_max'.$i),	
					'GRADE'					=> $this->input->post('grade'.$i),	
					// 'KETERANGAN'	 		=> $this->input->post('keterangan')
				);
				$this->pelajaran_model->insert_grading($data);
			}
		}
		$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
		redirect('grading/index/'.$kode_mp.'/'.$this->session->userdata('unitid').'/'.$this->session->userdata('tahunajaran')); 
	}
	
	function edit_grading($kode_mp)
    {
 		if ($this->cek_validasi() == FALSE){
			$data['status'] = 'edit';
			$data['param_id'] = $kode_mp."#".$this->session->userdata('unitid')."#".$this->session->userdata('tahunajaran');
			$data['tahunajaran'] = $this->pelajaran_model->getTa($this->session->userdata('unitid'));
			$data['pelajaran'] = $this->pelajaran_model->getMp($this->session->userdata('unitid'),$kode_mp);
			// $data['aspek_nilai'] = $this->pelajaran_model->getAspekUpdate($id_sekolah,$kode_mp);
			
			$data['rs_grading'] = $this->pelajaran_model->get_gradingID($kode_mp);
			$data['content'] = $this->load->view('form_grading',$data,true);
			$this->load->view('main',$data);
		}
		else{
			// if($this->cek_pelajaran_guru($this->input->post('kode_mp'),$this->input->post('tahun_ajaran'),$this->session->userdata('unitid'),$this->input->post('tingkat'),$this->input->post('kelas'),$this->input->post('semester'),$this->input->post('nip'))->jml > 0 and $this->cek_pelajaran_guru($this->input->post('kode_mp'),$this->input->post('tahun_ajaran'),$this->session->userdata('unitid'),$this->input->post('tingkat'),$this->input->post('kelas'),$this->input->post('semester'),$this->input->post('nip'))->ID_PG != $id_pg){
				// $data['status'] = 'edit';
				// $data['param_id'] = $kode_mp."#".$id_sekolah."#".$id_ta;
				// $data['tahunajaran'] = $this->pelajaran_model->getTa($id_sekolah);
				// $data['pelajaran'] = $this->pelajaran_model->getMp($id_sekolah,$kode_mp);
				// $data['aspek_nilai'] = $this->pelajaran_model->getAspek($id_sekolah,$kode_mp);
			
				// $data['rs_grading'] = $this->pelajaran_model->get_gradingID($kode_mp,$id_sekolah,$id_t);
				// $data['err_msg'] = 'Kode Mata Pelajaran telah ada dalam database.';
				// $data['content'] = $this->load->view('form_grading',$data,true);
				// $this->load->view('main',$data);
			// }else
				$this->update_pelajaran_guru($kode_mp);
		}            
    }
	
	function update_pelajaran_guru($kode_mp){
		// if($this->session->userdata('roleid')=='0'){ //diknas
			// $nama_sekolah = $this->input->post('nama_sekolah');
		// }else{
			// $nama_sekolah = $nama_sekolahp;
		// }
		$this->pelajaran_model->delete_grading($kode_mp, $this->session->userdata('unitid'),$this->session->userdata('tahunajaran'));
		for($i=1; $i<=10; $i++){
			if($this->input->post('nilai_min'.$i)!='' and $this->input->post('nilai_max'.$i)!='' and $this->input->post('grade'.$i)!=''){
				$data = array(
					'TAHUN_AJARAN'			=> $this->session->userdata('tahunajaran'),
					'ID_SEKOLAH'			=> $this->session->userdata('unitid'),
					'KODE_MATA_PELAJARAN'	=> $kode_mp,	
					// 'KODE_PENILAIAN'		=> $this->input->post('kode_penilaian'),	
					'NILAI_MIN'				=> $this->input->post('nilai_min'.$i),	
					'NILAI_MAX'				=> $this->input->post('nilai_max'.$i),	
					'GRADE'					=> $this->input->post('grade'.$i)
				);
				$this->pelajaran_model->insert_grading($data);
			}
		}
		
		$this->session->set_flashdata('suc_msg', 'Data berhasil diupdate.');
		redirect('grading/index/'.$kode_mp.'/'.$this->session->userdata('unitid').'/'.$this->session->userdata('tahunajaran')); 
	}
	
	//Delete
	function delete_grading($kode_mp)
	{
		$this->pelajaran_model->delete_grading($kode_mp);
		$this->session->set_flashdata('suc_msg', 'Data berhasil dihapus.');
		redirect('grading/index/'.$kode_mp.'/'.$this->session->userdata('unitid').'/'.$this->session->userdata('tahunajaran'));
		// $ta_ids_post_array = explode(",",$this->input->post('items'));
		// $msg = '';
		// foreach($ta_ids_post_array as $index => $ta_id){
			// if (isset($ta_id) && $ta_id != "") {
				// 
				// $msg .= "Data Grading berhasil dihapus.\n";
			// }
		// }
		// $this->output->set_header($this->config->item('ajax_header'));
		// $this->output->set_output($msg);
	}
	
}
?>
